<template>
  <el-container class="nav-bar">
    <el-header>
      <div class="logo">
      轻课·加特林
      </div>
      <div class="tabs">
        <el-menu :router="true" :default-active="activeIndex" class="tab-menu" mode="horizontal" @select="handleSelect">
          <el-menu-item index="/group-collection">群库</el-menu-item>
          <el-menu-item index="/message/template">推送</el-menu-item>
          <el-menu-item index="/count/countList">高级设置</el-menu-item>
        </el-menu>
      </div>
      <div class="right">
        <div class="current-woa">当前公众号：{{currentWoa.publicAccountNickname}}  </div>&nbsp;&nbsp;&nbsp;
        <el-popover
          ref="switch1"
          placement="bottom"
          width="800"
          trigger="click">
          <WoaToast></WoaToast>
        </el-popover>
        <el-button type="text" class="switch-woa" v-popover:switch1>&nbsp;&nbsp;切换&nbsp;&nbsp;</el-button>
        <div class="user-name">&nbsp;&nbsp;{{userName}} &nbsp;&nbsp;</div>
        <el-popover
          ref="user1"
          placement="bottom"
          width="50"
          trigger="hover">
          <el-button type="text" v-if="isSuperAdmin" class="user-action" @click="to('/user')">账号管理</el-button>
          <br v-if="isSuperAdmin">
          <el-button type="text" v-if="isSuperAdmin" class="user-action" @click="to('/wechat-offical-account')">公众号管理</el-button>
          <br v-if="isSuperAdmin">
          <el-button type="text" class="user-action" @click="logout">登出</el-button>
        </el-popover>
        <el-button type="text" class="user-btn" v-popover:user1>
          <div class="user-avatar" >
            <img v-if="userAvatar || userInfoAvatar" width="100%" height="100%" :src="userAvatar || userInfoAvatar" />
            <i v-else class="el-icon-picture"></i>
          </div>
        </el-button>
      </div>
    </el-header>
  </el-container>
</template>
<script>
  import _ from 'underscore';

  import auth from '../util/auth';
  import cookie from '../lib/cookie';
  import CONSTANT from '../constant/common';
  import WoaToast from './woa-toast.vue';

  export default {
    data() {
      return {
        isLogged: auth.isLogged(),
        userId: cookie(CONSTANT.COOKIE_USER_ID) || '',
        isSuperAdmin: cookie(CONSTANT.COOKIE_USER_ROLE) === 'ADMIN',
        userName: cookie(CONSTANT.COOKIE_USER_NICKNAME) || cookie(CONSTANT.COOKIE_USER_NAME) || '未知用户',
        userAvatar: cookie(CONSTANT.COOKIE_USER_PHOTOURL) || '',
      };
    },
    computed: {
      userInfoAvatar() {
        return this.$store.state.user.userDetail.imageData || '';
      },
      currentWoa() {
        return this.$store.state.woa.currentWoa;
      },
      activeIndex() {
        return this.$route.path;
      },
      userInfo() {
        return this.$store.state.login.loginObj;
      },
    },
    watch: {
      userInfo(nv) {
        if(nv && nv.status === 500) {
          return;
        }
        if (_.isEmpty(nv)) {
          return;
        }
        this.userName = nv[CONSTANT.COOKIE_USER_NICKNAME] || nv[CONSTANT.COOKIE_USER_NAME];
        this.isSuperAdmin = nv[CONSTANT.COOKIE_USER_ROLE] === 'ADMIN';
        this.userId = nv[CONSTANT.COOKIE_USER_ID];
        this.userAvatar = nv[CONSTANT.COOKIE_USER_PHOTOURL];
        const currentWoa = [...nv[CONSTANT.COOKIE_USER_WOA_LIST]][0];
        const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
          JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
        this.$store.dispatch('setCurrentWoa', _.isEmpty(localWoa) ? currentWoa : localWoa);
      },
    },
    components: {
      WoaToast,
    },
    methods: {
      handleTabClick(tab, e) {
        console.log(tab, e);
      },
      switchAccount() {

      },
      logout() {
        auth.clearUserInfo();
        localStorage.setItem(CONSTANT.STORAGE_LOCAL_WOA, '{}');
        // window.location.href = '/page/index.html';
        this.$router.push('/');
      },
      handleSelect(key, keyPath) {
        if (!this.isLogged) return;
        this.$store.dispatch('getLoginInfo', {
          userId: this.userId,
        }).then((res) => {
          // 不同角色的异常处理
          if (res.publicAccounts.length < 1 && res.role === 'ADMIN') { this.$router.push('/wechat-offical-account'); }
          if (res.publicAccounts.length < 1 && res.role === 'USER') {
            this.$message({
              type: 'warning',
              message: '当前账号无公众号，请联系管理员绑定公众号',
            });
            this.$router.push('/home');
          }
        });
        console.log(key, keyPath);
      },
      to(path) {
        this.$router.push(path);
      },
    },
    mounted() {
      // 中断首页获取数据
      // console.log('11111111111 nav-bar mounted ', window.location.hash);
      if (!this.isLogged) return;
      console.log('nav-bar mounted ', window.location.hash);
      this.$store.dispatch('getWoaList').then(() => {
        const woaList = this.$store.state.woa.woaList || [];
        if (!this.userAvatar && this.userId) {
          this.$store.dispatch('getLoginInfo', {
            userId: this.userId,
          });
        }

        // 判断和设置默认公众号以及保留切换过的公众号
        let localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ? JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : '';
        // 判断公众号是否解绑
        const selectedWoa = woaList.find(item => item.appId === localWoa.appId);
        localWoa = selectedWoa;
        const defaultWoa = localWoa || woaList[0];

        if (!_.isEmpty(defaultWoa) && _.isEmpty(this.currentWoa)) {
          this.$store.dispatch('setCurrentWoa', defaultWoa);
        } else {
          this.$message({
            type: 'warning',
            message: '当前账号无公众号，请联系管理员绑定公众号',
          });
          this.$router.push('/home');
          this.$store.dispatch('setCurrentWoa', {
            publicAccountNickname: '未知公众号',
          });
        }
      });
    },
  };
</script>
<style lang="less" scoped>
  .nav-bar {
    height: 61px;
    width: 100%;
    line-height: 61px;
    border-bottom: solid 1px #e6e6e6;
    .logo {
      width: 200px;
      float: left;
      font-size: 34px;
    }
    .tabs {
      float: left;
      .tab-menu {
        li {
          font-size: 20px !important;
        }
      }
    }
    .right {
      float: right;
      font-size: 14px;
      .current-woa, .switch-woa, .user-info, .user-name, .user-avatar, .user-btn {
        float: left;
      }
      .user-btn {
        margin: 0;
      }
      .user-action{
        display: block;
      }
      .user-avatar {
        width: 30px;
        height: 30px;
        border-radius: 15px;
        border: 1px #eee solid;
        text-align: center;
        line-height: 30px;
        font-size: 30px;
      }
      .switch-woa {
        margin-top: 10px;
        font-size: 14px;
      }
    }
  }
</style>
